//
//  GCDDeom1ViewController.m
//  多线程编程
//
//  Created by Guo Rui on 2017/7/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "GCDDeom1ViewController.h"

@interface GCDDeom1ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation GCDDeom1ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       [self startDownloadImage];
    });
}

- (void)startDownloadImage {
    
    self.label.text = @"正在下载图片";
    
    dispatch_queue_t queue = dispatch_queue_create("GCD.downloadImageQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    __block UIImage *image1 = nil;
    __block UIImage *image2 = nil;
    
    // 下载第一张图片
    dispatch_group_async(group, queue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://imgstore.cdn.sogou.com/app/a/100540002/879873.jpg"]];
        image1 = [UIImage imageWithData:imageData];
    });
    
    // 下载第二张图片
    dispatch_group_async(group, queue, ^{
        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://tupian.enterdesk.com/2012/0506/1/11.jpg"]];
        image2 = [UIImage imageWithData:imageData];
    });
    
    
    // 等待所有任务结束 方式一
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    CGSize size = self.imageView.bounds.size;
    UIGraphicsBeginImageContext(size);
    
    [image1 drawInRect:CGRectMake(0, 0, size.width, size.height / 2.f)];
    [image2 drawInRect:CGRectMake(0, size.height / 2.f, size.width, size.height / 2.f)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = newImage;
        self.label.text = @"图片合成完成";
    });
    
    /*
    // 等待所有任务结束 方式二
    __weak typeof(self) weakself= self;
    dispatch_group_notify(group, queue, ^{
        
        CGSize size = weakself.imageView.bounds.size;
        UIGraphicsBeginImageContext(size);
        
        [image1 drawInRect:CGRectMake(0, 0, size.width, size.height / 2.f)];
        [image2 drawInRect:CGRectMake(0, size.height / 2.f, size.width, size.height / 2.f)];
        
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        dispatch_async(dispatch_get_main_queue(), ^{
            weakself.imageView.image = newImage;
            weakself.label.text = @"图片合成完成";
        });
    });
     */
}

@end
